package bot;

import gui.BotGui;

import java.awt.AWTException;
import java.awt.Color;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import javax.swing.JTextArea;

public class FullCycleBot {
	
	private String url;
	private City city;
	private String date;
	private JTextArea code;
	private boolean cleanup;
	
	public FullCycleBot(String url, City city, String date, JTextArea code, boolean cleanup){
		this.url = url;
		this.city = city;
		this.date = date;
		this.code = code;
		this.cleanup = cleanup;
	}
	
	public void edit(){
		Thread t = new Thread(new OpenSiteThread(url));
		t.start();
		try{
			t.join();
		} 
		catch (InterruptedException e){
			e.printStackTrace();
		}
		long start = System.currentTimeMillis();
		while (System.currentTimeMillis() - start < 400);
		
		AutoEdit auto = new AutoEdit();
		auto.edit(url, city, date, code, cleanup);
	}
	
	public class OpenSiteThread implements Runnable{
		
		private String url;
		
		public OpenSiteThread(String url){
			this.url = url;
		}
		
		@Override
		public void run() {
			try {
				Robot robo = new Robot();
				robo.mouseMove(300, 65);
				robo.mousePress(InputEvent.BUTTON1_MASK);
				robo.mouseRelease(InputEvent.BUTTON1_MASK);
				//highlight and then delete the url currently in the browser
				robo.keyPress(KeyEvent.VK_CONTROL);
				robo.keyPress(KeyEvent.VK_A);
				robo.keyRelease(KeyEvent.VK_A);
				robo.keyRelease(KeyEvent.VK_CONTROL);
				robo.keyPress(KeyEvent.VK_DELETE);
				robo.keyRelease(KeyEvent.VK_DELETE);
				//put the url on the paste buffer then paste it in
				Util.setPasteBuffer(url);
				robo.keyPress(KeyEvent.VK_CONTROL);
				robo.keyPress(KeyEvent.VK_V);
				robo.keyRelease(KeyEvent.VK_V);
				robo.keyRelease(KeyEvent.VK_CONTROL);
				//submit the url
				robo.keyPress(KeyEvent.VK_ENTER);
				robo.keyRelease(KeyEvent.VK_ENTER);
				
				boolean keepGoing = true;
				while(keepGoing){
					keepGoing = false;
					for (int i = 850; i < 860; i++){
						//was 290 when wikinic banner was up
						Color test = robo.getPixelColor(i, BotGui.height);
						int r = test.getRed();
						int g = test.getGreen();
						int b = test.getBlue();
						if (!(r >= 236 && r <= 240)){
							keepGoing = true;
						}
						if (!(g >= 244 && g <= 248)){
							keepGoing = true;
						}
						if (!(b >= 248 && b <= 252)){
							keepGoing = true;
						}
					}
				}
			} catch (AWTException e) {
				e.printStackTrace();
			}
		}
		
	}
}
